#!/usr/bin/env python
#coding=utf-8

import os
import sys
import re
import zipfile

if __name__ == '__main__':
	if len(sys.argv) != 3:
		print 'usage: create.list.py [folder path] [output file name]'
		sys.exit(0)
	
	_p = sys.argv[1]
	_o = sys.argv[2]
	
#	_p = 'K:\\90DayTemp\\mfeng\\p019r037'
#	_o = 'K:\\90DayTemp\\mfeng\\p019r037.txt'
	
	_map = {}
	for _root, _paths, _files in os.walk(_p):
		for _f in _files:
			if _f.endswith('.zip'):
				_zip = zipfile.ZipFile(os.path.join(_root, _f), 'r')
				for _f in _zip.infolist():
					_m = re.match('\w{2}\d{9}(\d{2})(\d{3})\d{2}\..+', _f.filename)
					if _m:
						_year = int(_m.group(1))
						if _year < 50:
							_year += 2000
						else:
							_year += 1900
							
						_map[_year * 1000 + int(_m.group(2))] = _f.filename.split('.')[0]
						break
	
	if len(_map) == 0:
		print 'warning: not found any dataset'
		sys.exit(0)
	
	_keys = _map.keys()
	_keys.sort()
	
	_out = file(_o, 'w')
	
	_out.write('StartOfImageList\n')
	_out.write(_p + '\n')
	
	print 'found', len(_keys)

	for _k in _keys:
		print '', _map[_k]
		
		_out.write(_map[_k] + '\n')
	
	_out.write('\nEndOfImageList\n')
	_out.close()

	print '....................'
	print 'output file created'
	
